package com.cntcdt.api.utils;

import static java.util.Arrays.asList;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.cntcdt.api.db.dao.ShopDao;
import com.cntcdt.api.db.model.ShopModel;
import com.cntcdt.api.db.mongodb.NearSearch;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;

public class NearyUpdateToMongoDBUtils {
	public static void main(String args[]){
//		mysqlToMongoDB();
//		deleteCollection();
//		updateMongoDB(1);
//		NearbyUserShopModel nearby = NearbyUserShopDao.getInstance().findByPrimaryKey(1);
//		insertMongoDB(nearby);
//		CdtUserModel user = CdtUserDao.getInstance().findByPrimaryKey(1000045961);
//		updateUsetToNearByMongoDB(user);
//		updateUsetToNearByMongoDB(user,0);
//		insertMongoDB(user);
//		insertShopToNearbyMongoDB();
//		createIndex();
//		if(findByUserIdToNearbyMongoDB(1000024117) > 0){
//			LogUtils.log.info("有数据");
//		}
//		else{
//			LogUtils.log.info("无数据");
//		}
//		List<CdtUserModel> userlist = CdtUserDao.getInstance().findByName();
//		for(CdtUserModel user : userlist){
//			System.out.println(user.getId());
//			updateUsetToNearByMongoDB(user,0);
//		}
//		List<ShopModel> shopList = ShopDao.getInstance().findByBeforeId(41);
//		for(ShopModel shop : shopList){
//		ShopModel shop = ShopDao.getInstance().findByPrimaryKey(2);
//			 insertMoreShopToNearbyMongoDB(shop);
//		}
//		updateMoreShopToNearbyMongoDB();
		//更新附近列表设备
//		updateShop();
//		System.exit(0);
	}
	
//	/**
//	 * 更新一条附近列表用户信息
//	 * @param user
//	 */
//	public static void updateUsetToNearByMongoDB(CdtUserModel user){
//		try{
//			 int versionI = 0;
//			if(user.getVersion() != null && !user.getVersion().equals("")){
//		        String versionInt = user.getVersion().replaceAll("\\D", "");
//		        versionI = Integer.parseInt(versionInt);
//			}
//			
//			double lat = 0;
//			double lng = 0;
//			
//			if(user.getLat() != null){
//				lat = user.getLat();
//				lng = user.getLng();
//			}
//				
//		LogUtils.log.info("isBorrow=============="+user.getIsBorrow());
//			Document newDocument1 =  new Document("type", "1")
//			.append("coord", asList(lng,lat ))
//			.append("isBorrow", user.getIsBorrow())
//			.append("userId", user.getId())
//			.append("shopId",0)
////			.append("isOpen", isOpen)
//			.append("version", versionI);
//			
//			LogUtils.log.info("lat=="+user.getLat()+"lng=="+user.getLng() );
//			if(user.getLat() == null){
//				LogUtils.log.info("lat=="+user.getLat()+"lng=="+user.getLng() );
//				newDocument1.append("isCoord", 0);
//			}
//			else{
//				newDocument1.append("isCoord", 1);
//			}
//			
//			Document newDocument = new Document("$set",newDocument1);
//
//			NearSearch.db.getCollection("cdt_nearby_user_shop").updateOne(new Document("userId", user.getId()), newDocument);
//		}
//		catch(Exception e){
//			e.printStackTrace();
//		}
//	}
//	
//	/**
//	 * 更新一条附近列表用户信息，可控制是否打开
//	 * @param user
//	 * @param isOpen
//	 */
//	public static void updateUsetToNearByMongoDB(CdtUserModel user,int isOpen){
//		try{
//			 int versionI = 0;
//			if(user.getVersion() != null && !user.getVersion().equals("")){
//		        String versionInt = user.getVersion().replaceAll("\\D", "");
//		        versionI = Integer.parseInt(versionInt);
//			}
//				
//			
//			Document newDocument = new Document("$set",new Document("type", "1")
//				.append("coord", asList(user.getLng(), user.getLat()))
//				.append("isBorrow", user.getIsBorrow())
//				.append("userId", user.getId())
//				.append("shopId",0)
//				.append("isOpen", isOpen)
//				.append("version", versionI)
//			);
//			NearSearch.db.getCollection("cdt_nearby_user_shop").updateOne(new Document("userId", user.getId()), newDocument);
//		}
//		catch(Exception e){
//			e.printStackTrace();
//		}
//	}	
//	
//	/**
//	 * 在附近列表插入一条用户数据
//	 * @param user
//	 */
//	public static void insertUserToNearbyMongoDB(CdtUserModel user){
//		try{
//			if(user.getLat() == null){
//				user.setLat(0.0);
//			}
//			if(user.getLng() == null){
//				user.setLng(0.0);
//			}
//			if(user.getIsBorrow() == null){
//				user.setIsBorrow(0);
//			}
//			int isOpen = 1;
////			if(user.getLat() <= 0 && user.getLng() <=0){
////				isOpen = 0;
////			}
//			 int versionI = 0;
//			if(user.getVersion() != null){
//		        String versionInt = user.getVersion().replaceAll("\\D", "");
//		        versionI = Integer.parseInt(versionInt);
//			}
//			
//			NearSearch.db.getCollection("cdt_nearby_user_shop").insertOne(
//					new Document("type", "1")
//					.append("coord", asList(user.getLng(), user.getLat()))
//					.append("isBorrow", user.getIsBorrow())
//					.append("userId", user.getId())
//					.append("shopId", 0)
//					.append("isOpen", isOpen)
//					.append("version", versionI)
//			                );
//		}
//		catch(Exception e){
//			e.printStackTrace();
//		}
//	}
	
	/**
	 * 查询一条附近列表用户数据
	 * @param userId
	 * @return
	 */
	public static int findByUserIdToNearbyMongoDB(int userId){
		try{
			final List<Integer> result = new ArrayList<Integer>();
		    BasicDBObject locQuery = new BasicDBObject("userId", userId);
		    LogUtils.log.info(locQuery+"");
		    FindIterable<Document> iterable = NearSearch.db.getCollection("cdt_nearby_user_shop").find(locQuery);
		    iterable.forEach(new Block<Document>() {
			    public void apply(final Document document) {
			        LogUtils.log.info(document+"");
			        result.add(document.getInteger("userId"));
			    }
		    });
		    return result.size();
		}
		catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
	
	/**
	 * 查询一条附近列表设备
	 * @param shopId
	 * @return
	 */
	public static int findByShopIdToNearbyMongoDB(int shopId){
		try{
			final List<Integer> result = new ArrayList<Integer>();
		    BasicDBObject locQuery = new BasicDBObject("shopId", shopId);
		    LogUtils.log.info(locQuery+"");
		    FindIterable<Document> iterable = NearSearch.db.getCollection("cdt_nearby_user_shop").find(locQuery);
		    iterable.forEach(new Block<Document>() {
			    public void apply(final Document document) {
			        LogUtils.log.info(document+"");
			        result.add(document.getInteger("userId"));
			    }
		    });
		    return result.size();
		}
		catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
	
//	/**
//	 * 插入所有用户到列表中
//	 */
//	public static void insertMoreUserToNearbyMongoDB(){
//		try{
//			List<CdtUserModel> userList = CdtUserDao.getInstance().findAll();
//			for(CdtUserModel user : userList){
//				NearSearch.db.getCollection("cdt_nearby_user_shop").insertOne(
//						new Document("type", "1")
//						.append("coord", asList(user.getLng(), user.getLat()))
//						.append("isBorrow", user.getIsBorrow())
//						.append("userId", user.getId())
//						.append("shopId", 0)
//				                );
//			}
//		}
//		catch(Exception e){
//			e.printStackTrace();
//		}
//	}
	
	/**
	 * 插入一条设备数据到附近列表
	 * @param shop
	 */
	public static void insertMoreShopToNearbyMongoDB(ShopModel shop){
		try{
//			List<ShopModel> shopList = ShopDao.getInstance().findAll();
//			for(ShopModel shop : shopList){
				if(shop.getOpStatus() == 0){
					NearSearch.db.getCollection("cdt_nearby_user_shop").insertOne(
							new Document("type", "2")
							.append("coord", asList(shop.getLng(), shop.getLat()))
							.append("isBorrow", 0)
							.append("userId", 0)
							.append("shopId", shop.getId())
							.append("isOpen", 1)
							.append("version", 260)
					                );
				}
//			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 更新一条附近列表设备数据
	 * @param shop
	 */
	public static void updateMoreShopToNearbyMongoDB(ShopModel shop){
		try{
				LogUtils.log.info(shop.getId()+"");
					Document newDocument = new Document("$set",new Document("type", "2")
					.append("coord", asList(shop.getLng(), shop.getLat()))
					.append("isBorrow", 0)
					.append("userId", 0)
					.append("shopId",shop.getId())
					.append("isOpen", 1)
					.append("version", 260)
					);
					NearSearch.db.getCollection("cdt_nearby_user_shop").updateOne(new Document("shopId", shop.getId()), newDocument);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	public static void createIndex(){
		MongoClient mongoClient = new MongoClient("183.131.145.141", 27017);
		MongoDatabase db = mongoClient.getDatabase("cdt");
		db.getCollection("cdt_nearby_user_shop").createIndex(new Document("coord", "2dsphere"));
	}
	
	public static void deleteCollection(){
		MongoClient mongoClient = new MongoClient("183.131.145.141", 27017);
		MongoDatabase db = mongoClient.getDatabase("cdt");
		db.getCollection("cdt_nearby_user_shop").drop();
		mongoClient.close();
	}
	
    private static void deleteColData(int shopId){  
    	NearSearch.db.getCollection("cdt_nearby_user_shop").deleteOne(new Document("shopId", shopId));
    }
	
    
    /**
     * 更新附近列表的设备
     */
	public static void updateShop(ShopModel shop){
//		List<ShopModel> shopList = ShopDao.getInstance().findAll();
//		for(ShopModel shop : shopList){
			if(shop.getOpStatus() == 0){
				int isHave = findByShopIdToNearbyMongoDB(shop.getId());
				if(isHave == 1){
					System.out.println("更新一台设备----"+shop.getId());
					updateMoreShopToNearbyMongoDB(shop);
				}
				else{
					System.out.println("添加一台设备----"+shop.getId());
					insertMoreShopToNearbyMongoDB(shop);
				}
			}
			else{
				int isHave = findByShopIdToNearbyMongoDB(shop.getId());
				if(isHave == 1){
					System.out.println("删除一台设备----"+shop.getId());
					deleteColData(shop.getId());
				}
			}
//		}
	}
	
}
